package com.example.fushuang.balabala.client;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by admin on 2016/10/13.
 */

public class OkHttpUtil extends AbstractHttpUtil{

    private final OkHttpClient mOkHttpClient;

    public OkHttpUtil() {
        mOkHttpClient = new OkHttpClient();
    }

    @Override
    public void doGetDataAsync(String url, final NetCallback callback) {
        Request.Builder builder = new Request.Builder();
        Request request = builder.url(url).get()
                .addHeader("User-Agent", "BiLiBiLi WP Client/4.20.0 (orz@loli.my)")
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                throw new RuntimeException("网络故障");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String reqUrl = call.request().url().toString();
                int code = response.code();
                byte[] data = response.body().bytes();
                //利用传入的接口,返回调用的ClientApi中对字节数组进行解析json,在这里解析成实体类
                //利用eventbus直接发送不太好,数据逻辑封装性感觉比较乱,虽然我特么的也不喜欢这样调接口
                callback.onSuccess(reqUrl,code,data);
            }
        });
    }

}
